package io.github.lee.repository.qb.repository

import android.content.Context
import androidx.core.net.toUri
import io.github.lee.repository.qb.api.ApiModule
import io.github.lee.repository.qb.dao.SessionDao
import io.github.lee.repository.qb.data.QbSession
import io.github.lee.repository.qb.di.http.HttpModule
import io.github.lee.repository.qb.domain.Response
import javax.inject.Inject

private const val LOGIN_PATH = "api/v2/auth/login"

class AuthRepository @Inject constructor(
    private val dao: SessionDao
) : BaseRepository() {

    suspend fun login(
        context: Context,
        sessionName: String, host: String,
        username: String, password: String,
    ): Response<QbSession> {

        HttpModule.resetNetwork(context, host)

        val url = host.toUri().buildUpon()
            .appendEncodedPath(LOGIN_PATH)
            .toString()
        val response = ApiModule.authApi().login(url, username, password)

        val session = QbSession(
            null, sessionName, host, username, password,
        )
        val resultId = dao.insert(session)
        session.id = resultId
        return Response(response.code, response.msg, session)
    }
}